import styles from './synthesisHistory.module.scss';
import MlsAudio from '@/components/common/mlsAudio';
import { ICON_PATHS } from '@/assets/images/constants';
import {
  Image,
  Button,
  Popover,
  Slider,
  InputNumber,
  Message,
  Empty,
} from '@arco-design/web-react';
import { useState, useEffect, useCallback } from 'react';
import MlsModal from '@/components/common/mlsModal';
import sharedWebSocket from '@/services/sharedWebSocket.jsx';
import { useLoading } from '@/components/common/mlsLoading/laodingText';
import { downloadAudio } from '@/utils/common';
import { timbreAdjust } from '@/api/audio';
import { synthesisHistoryListDelete, synthesisHistoryListGet } from '@/api/common';

export default function SynthesisHistory() {
  // 使用对象存储每一行的Popover可见状态
  const [visibleIndex, setVisibleIndex] = useState(-1);
  const [modalVisible, setModalVisible] = useState(false);

  const [toolSize, setToolSize] = useState(1);
  const [voiceLoudness, setVoiceLoudness] = useState(-40);
  const [currentVoiceSpeed, setCurrentVoiceSpeed] = useState(0);
  const [audioDuration, setAudioDuration] = useState(0);
  const { showLoading, hideLoading } = useLoading();
  const [audioList, setAudioList] = useState([]);
  const [curSelectedAudio, setCurSelectedAudio] = useState({});

  // 点击外部区域关闭Popover的效果
  useEffect(() => {
    const handleClickOutside = event => {
      // 检查点击事件是否发生在所有Popover相关元素外部
      // 包含：触发按钮和弹窗内容本身
      const isClickOutside =
        !event.target.closest('[data-popover]') && !event.target.closest('[data-popover-trigger]');

      if (isClickOutside && visibleIndex !== -1) {
        setVisibleIndex(-1);
      }
    };

    // 添加事件监听
    document.addEventListener('mousedown', handleClickOutside);

    // 清理函数
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [visibleIndex]);

  // 处理Popover点击事件
  const handlePopoverClick = index => {
    // 如果点击的是当前已打开的Popover，则关闭它；否则，打开点击的Popover并关闭其他所有
    setVisibleIndex(prevIndex => (prevIndex === index ? -1 : index));
  };

  // 提供给Popover组件的onVisibleChange回调
  const handleVisibleChange = (visible, index) => {
    // 当Popover被内部逻辑关闭时（如点击遮罩层），同步更新状态
    if (!visible && visibleIndex === index) {
      setVisibleIndex(-1);
    }
  };

  const handleAdjust = useCallback((index, voiceSpeed) => {
    setVisibleIndex(-1);
    // 点击调整按钮时，将当前行数据传递给弹窗
    setCurSelectedAudio(audioList[index]);
    // 处理参数调节逻辑
    console.log(`voiceSpeed: ${voiceSpeed}s`);
    // 假设从音频获取时长，这里简化处理
    setCurrentVoiceSpeed(voiceSpeed);
    setAudioDuration(voiceSpeed);
    // 重置toolSize为初始值1
    resetConfig();

    setModalVisible(true);
  }, [audioList]);

  // 双向绑定 - 处理slider变化时更新input
  const onToolSizeChange = value => {
    setToolSize(value);
    // 根据倍速计算对应的时长
    const calculatedDuration = audioDuration * (1 / value);
    setCurrentVoiceSpeed(Math.round(calculatedDuration));
  };

  // 双向绑定 - 处理input变化时更新slider
  const onVoiceSpeedChange = value => {
    console.log('currentVoiceSpeed', value);
    if (typeof value !== 'number' || isNaN(value)) return;

    setCurrentVoiceSpeed(value);
    // 根据时长计算对应的倍速
    const calculatedSpeed = audioDuration / value;
    // 限制在slider的范围内
    const clampedSpeed = Math.min(Math.max(calculatedSpeed, 0.5), 2);
    setToolSize(clampedSpeed);
  };

  const resetConfig = () => {
    setToolSize(1);
    setVoiceLoudness(-40);
  }

  const onVoiceLoudnessChange = value => {
    console.log('voiceLoudness', value);

    setVoiceLoudness(value);
  };
  const repeatCreat = useCallback(() => {
    // 重新合成
    let obj = {
      audioUrl: curSelectedAudio.audioUrl,
      duration: currentVoiceSpeed,
      loudness: voiceLoudness,
      historyId: curSelectedAudio?.historyId,
    };
    console.log('repeatCreat', obj);
    showLoading('调节中...');
    timbreAdjust(obj)
      .then(res => {
        if (res.code === 200) {
        }
      })
      .catch(err => {
        Message.error(err.message || '调节失败');
        hideLoading();
      });

    setModalVisible(false);
  }, [currentVoiceSpeed, voiceLoudness, curSelectedAudio.audioUrl]);

  const renderModalContent = useCallback(() => {
    // 根据音频时长和slider的最大最小倍速计算InputNumber的最大最小值
    const minDuration = Math.round(audioDuration * (1 / 2)); // 2x速度对应的最短时长
    const maxDuration = Math.round(audioDuration * (1 / 0.5)); // 0.5x速度对应的最长时长

    return (
      <div className={styles.brushSizeContainer}>
        <div className={styles.brushSizeWrapper}>
          <div>阅读语速</div>
          <div className={styles.brushSizeSliderContainer}>
            <div className={styles.brushSizeIcon}>
              <div className={styles.brushSizeIconSmall}>0.5x</div>
            </div>
            <Slider
              className={styles.slider}
              min={0.5}
              max={2}
              step={0.1}
              value={toolSize}
              onChange={onToolSizeChange}
            />
            <div className={styles.brushSizeIcon}>
              <div className={styles.brushSizeIconLarge}>2x</div>
            </div>
          </div>
          <div className={styles.brushSizeInput}>
            <InputNumber
              mode="button"
              min={minDuration}
              value={currentVoiceSpeed}
              suffix="S"
              step={1}
              max={maxDuration}
              onChange={onVoiceSpeedChange}
            />
          </div>
        </div>
        <div className={styles.brushSizeWrapper}>
          <div>音频响度</div>
          <div className={styles.brushSizeSliderContainer}>
            <div className={styles.brushSizeIcon}>
              <div className={styles.brushSizeIconSmall}>-80</div>
            </div>
            <Slider
              className={styles.slider}
              min={-80}
              max={0}
              step={1}
              value={voiceLoudness}
              onChange={onVoiceLoudnessChange}
            />
            <div className={styles.brushSizeIcon}>
              <div className={styles.brushSizeIconLarge}>0</div>
            </div>
          </div>
          <div className={styles.brushSizeInput}>
            <InputNumber
              mode="button"
              max={0}
              min={-80}
              value={voiceLoudness}
              suffix="LUFS"
              step={1}
              onChange={onVoiceLoudnessChange}
            />
          </div>
        </div>
      </div>
    );
  },  [audioDuration, voiceLoudness, toolSize, currentVoiceSpeed, onToolSizeChange, onVoiceSpeedChange]);

  const handleDownload = useCallback((url, fileName) => {
    console.log('url', url, fileName);
    
    downloadAudio(url, fileName);
  }, [downloadAudio]);

  const fetchAudioList = async () => {
    showLoading('加载中...'); // 显示加载状态
    const res = await synthesisHistoryListGet({
      operType: 'commandGenerationVoice',
    });
    if (res?.code === 200) {
      let list = (res?.data?.list || []).map(item => {
        let obj = item.operInfo ? JSON.parse(item.operInfo) : {}; 
        return {
          ...item,
          audioUrl: item.fileUrl,
          audioName: obj.audioName || '',
          duration: obj.duration ? Number(obj.duration) : 0,
        }
      })
      setAudioList(list);
    }
    hideLoading(); // 隐藏加载状态
  };
  
  const handleDelete = useCallback(
    index => {
      setVisibleIndex(-1);
      // 处理删除逻辑
      // 根据historyId删除对应的数据
      const historyId = audioList[index].historyId;
      console.log(`删除historyId ${historyId} 数据`);
      if (!historyId) return;
      // 调用删除接口
      synthesisHistoryListDelete({
        historyId,
      })
        .then(res => {
          if (res?.code === 200) {
            // 删除成功后，更新本地数据
            Message.success('删除成功');
            fetchAudioList();
          }
        })
        .catch(err => {
          Message.error('删除失败');
        });
    },
    [audioList, fetchAudioList]
  );

  useEffect(() => {
    // 初始化查询列表
    fetchAudioList();
  },[]);
  
  useEffect(() => {
    const handleOpt = data => {
      console.log('socket---', data);
      if (data?.func === 'generate_voice_success') {
        // 再去查询列表
        hideLoading();
        fetchAudioList();
      }
      if (data?.func === 'generate_voice_fail') {
        hideLoading();
        Message.error('合成失败');
      }
      if (data?.func === 'adjustment_audio_success') {
        hideLoading();
        fetchAudioList();
      }
      if (data?.func === 'adjustment_audio_fail') {
        hideLoading();
        Message.error('调节失败');
      }
    };

    sharedWebSocket.on('resp', handleOpt);
    return () => {
      sharedWebSocket.off('resp', handleOpt);
    };
  }, [hideLoading]);
  return (
    <div className={styles.synthesisHistory}>
      <div className={`${styles.voiceContentList} ${audioList.length ? null : styles.center}`}>
        {audioList.length ? (
          audioList.map((item, index) => (
            <div className={styles.audioItem} key={item.historyId}>
              {/* <div className={styles.audioItemTitle}>
              <div className={styles.audioDeviceType}>麦克风1</div>
            </div> */}
              <div className={styles.audioContent}>
                <MlsAudio
                  src={item.audioUrl}
                  title={item.audioName}
                  progressHeight={20}
                  showVolumeControl={false}
                  showELseControl={false}
                  progressBgColor="rgba(255, 255, 255, 0.2)"
                />
              </div>
              <div className={styles.otherActions}>
                <Button
                  type="primary"
                  className={styles.downLoadButton}
                  onClick={() => handleDownload(item.audioUrl, item.audioName)}>
                  <Image
                    className={styles.downloadIcon}
                    src={ICON_PATHS.DOWNLOAD_ICON}
                    alt="下载"
                    draggable={false}
                    preview={false}
                  />
                  下载
                </Button>
                <Popover
                  trigger="click"
                  popupVisible={visibleIndex === index}
                  title=""
                  color="#191920"
                  position="br"
                  data-popover="content"
                  className={styles.audioPopover}
                  onVisibleChange={visible => handleVisibleChange(visible, index)}
                  content={
                    <ul className={styles.popoverContent}>
                      <li onClick={() => handleDelete(index)}>删除</li>
                      <li onClick={() => handleAdjust(index, item.duration)}>参数调节</li>
                    </ul>
                  }>
                  <button
                    className={styles.otherActionsButton}
                    aria-label="更多操作"
                    onClick={() => handlePopoverClick(index)}
                    data-popover-trigger="true">
                    <Image
                      src={ICON_PATHS.MORE_ICON}
                      alt="更多操作"
                      width={24}
                      height={24}
                      draggable={false}
                      preview={false}
                    />
                  </button>
                </Popover>
              </div>
            </div>
          ))
        ) : (
          <Empty description="暂无数据" />
        )}
      </div>
      <MlsModal
        visible={modalVisible}
        modalProps={{
          title: '参数调节',
          width: 768,
          height: 260,
          maskClosable: false,
          className: `custom-semi-modal-style`,
        }}
        onCancel={() => setModalVisible(false)}
        onConfirm={repeatCreat}
        children={renderModalContent()}
      />
    </div>
  );
}
